#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""检查向量化状态和文件完整性"""

import os
import sys

# Windows 控制台编码设置
if sys.platform == 'win32':
    import codecs
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')

# 添加项目根目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from app.models.database import engine
from sqlalchemy.orm import sessionmaker
from app.models.document import Document
from app.core.config import settings

def main():
    Session = sessionmaker(bind=engine)
    db = Session()
    
    try:
        docs = db.query(Document).all()
        print(f'\n=== 文档向量化状态 ===')
        print(f'总文档数: {len(docs)}')
        
        vectorized = [d for d in docs if d.is_vectorized]
        not_vectorized = [d for d in docs if not d.is_vectorized]
        
        print(f'已向量化: {len(vectorized)}')
        print(f'未向量化: {len(not_vectorized)}')
        
        if not_vectorized:
            print(f'\n未向量化的文档:')
            for d in not_vectorized:
                print(f'  - {d.title} (ID: {d.id[:8]}...)')
        
        print(f'\n=== 向量文件完整性检查 ===')
        for d in vectorized:
            vector_path = os.path.join(settings.VECTOR_STORE_DIR, f"{d.id}.faiss")
            index_exists = os.path.exists(f"{vector_path}.index")
            meta_exists = os.path.exists(f"{vector_path}.meta")
            
            status = "✅" if (index_exists and meta_exists) else "❌"
            print(f'{status} {d.title[:40]:40} | DB_vector_id: {d.vector_store_id[:8] if d.vector_store_id else "None":8}... | Files: index={index_exists}, meta={meta_exists}')
            
            # 如果数据库中的 vector_store_id 和文档 ID 不一致，标记出来
            if d.vector_store_id and d.vector_store_id != d.id:
                print(f'   ⚠️  警告: vector_store_id ({d.vector_store_id[:8]}...) != document_id ({d.id[:8]}...)')
        
        print(f'\n=== 总结 ===')
        print(f'✅ 数据完整的文档: {sum(1 for d in vectorized if os.path.exists(os.path.join(settings.VECTOR_STORE_DIR, f"{d.id}.faiss.index")))}')
        print(f'❌ 数据缺失的文档: {sum(1 for d in vectorized if not os.path.exists(os.path.join(settings.VECTOR_STORE_DIR, f"{d.id}.faiss.index")))}')
        
    finally:
        db.close()

if __name__ == "__main__":
    main()

